package twopointer;

/**
 * 接雨水（存水问题）
 * https://leetcode-cn.com/problems/trapping-rain-water/
 */
public class TrappingRainWater {

    public static void main(String[] args) {
        int[] nums = {0,1,0,2,1,0,1,3,2,1,2,1};
        System.out.println(new TrappingRainWater().trap(nums));
    }

    public int trap(int[] height) {
        if (height == null || height.length == 0){
            return 0;
        }
        int len = height.length;
        int left = 0;
        int right = len - 1;
        int leftHeight = height[left];
        int rightHeight = height[right];
        int sum = 0;
        while (left < right) {
            if (leftHeight < rightHeight) {
                if (leftHeight > height[left + 1]) {
                    // 当前left高度大于下一个left的高度，计算积水量
                    sum += leftHeight - height[left + 1];
                } else {
                    // 当前left高度小于下一个left高度，替换leftHeight
                    leftHeight = height[left + 1];
                }
                left++;
            } else {
                if (rightHeight > height[right - 1]) {
                    // 当前right高度大于下一个right高度，计算积水量
                    sum += rightHeight - height[right - 1];
                } else {
                    // 当前right高度小于下一个right高度，替换rightHeight
                    rightHeight = height[right - 1];
                }
                right--;
            }
        }
        return sum;
    }

}
